package com.xxkj.drugtraceability.ui.drugstorage

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.GsonBuilder
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.bean.BoxCodeRequest
import com.xxkj.drugtraceability.bean.DrugInStorageBean
import com.xxkj.drugtraceability.bean.DrugInfoBean
import com.xxkj.drugtraceability.net.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/10 16:15
 * description:
 */
class DrugStorageViewModel(
    application: Application,
    private val repository: DrugStorageRepository
) : BaseViewModel(application) {
    var dataList = MutableLiveData<List<DrugInStorageBean>>()
    var uiState = MutableLiveData<UiState<Boolean>>()
    var barcode = ""
    fun queryDrugInStorageInfo(barcode: String) {
        this.barcode = barcode
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                uiState.postValue(UiState(isLoading = true))
                val result = repository.queryDrugInStorageInfo(barcode)
                if (result is Result.Success) {
                    if (result.data.data.isNotEmpty()) {
                        dataList.postValue(result.data.data!!)
                    } else dataList.postValue(mutableListOf())
                    uiState.postValue(UiState(isLoading = false))
                } else if (result is Result.Error) {
                    uiState.postValue(
                        UiState(
                            isLoading = false,
                            isError = result.errorData ?: result.exception.message
                        )
                    )
                }
            }
        }
    }

}